package com.podmanager.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Random;

import android.os.Environment;
import android.util.Log;

public class FileUtility {
	private static String MAIN_DIRECTORY = Environment.getExternalStorageDirectory().getAbsolutePath()+"/podmanager";
	private static String FEED_DIRECTORY = MAIN_DIRECTORY+"/.rss";
	private static String IMAGE_DIRECTORY = MAIN_DIRECTORY+"/.images";
	private static String PODCAST_DIRECTORY = MAIN_DIRECTORY+"/podcasts";
	public static File getFeedDirectory()
	{
		File file=new File(FEED_DIRECTORY);
		return validateDirectory(file);
	}
	public static File getImageDirectory()
	{
		File file=new File(IMAGE_DIRECTORY);
		return validateDirectory(file);
	}
	public static File getPodcastDirectory()
	{
		File file=new File(PODCAST_DIRECTORY);
		return validateDirectory(file);
	}

	/**
	 * @param file
	 * ensures that Directory exists before returning the File.
	 * also ensures that directory will have .nomedia file so 
	 * that android media system doesn't include this directory
	 * Returns null If directory creation is needed, but fails
	 */
	private static File validateDirectory(File file) {
		if (file.exists())
			if(file.isDirectory())
				return file;
		if (!file.mkdirs())
			return null;
		File nomedia = new File(file.getAbsolutePath(),".nomedia");
		try {
			nomedia.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}
	
	/*
	 * Creates a file name with a random number such that
	 * fileX.xml where X is a random number.
	 */
	public static String getRandomFileName(int seed) {
		Random generator = new Random(seed);
		int num = generator.nextInt();
		String randomFileName = String.format(Locale.US,"file%d.xml", num);
		return randomFileName;
	}
	
	/*
	 * Creates a time stamped file name.
	 */
	public static String getTimeStampedFileName() {
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.US).format(Calendar.getInstance().getTime());
		String fileName = String.format("rss%s.xml", timeStamp);
		return fileName;
	}
	
	public static void deleteDirectory(String dirPath)
	{
		File dir = new File(dirPath);
		if (dir.isDirectory()) 
		{
	        String[] children = dir.list();
	        for (int i = 0; i < children.length; i++) {
	        	File child =new File(dir, children[i]);
	        	if(child.isDirectory())
	        	{
	        		deleteDirectory(child.getAbsolutePath());
	        	}
	        	else
	        	{
	        		if(child.delete()==false)
	        			Log.w("Delete File", "Failed to delete:"+child.getAbsolutePath());
	        	}
	        }
    		if(dir.delete()==false)
    			Log.w("Delete File", "Failed to delete:"+dir.getAbsolutePath());
	    }
	}
	
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		boolean isDeleted = false;
		
		if (file.exists()) {
			try {
				isDeleted = file.delete();
			}
			catch (Exception e) {
				Log.d("in deleteFile", "cannot delete file");
			}
		}
		return isDeleted;
	}

	public static String getDirectoryForEpisodes(String subscriptionID)
	{
		return validateDirectory(new File (getPodcastDirectory(), "/"+subscriptionID)).getAbsolutePath();
	}
	public static String getDirectoryForEpisodes(Long subscriptionID)
	{
		return getDirectoryForEpisodes(subscriptionID+"");
	}
	
	public static String getDirectoryForImages(String subscriptionID)
	{
		return validateDirectory(new File (getImageDirectory(), "/"+subscriptionID)).getAbsolutePath();
	}
	public static String getDirectoryForImages(Long subscriptionID)
	{
		return getDirectoryForImages(subscriptionID+"");
	}
	
	
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }	
}
